import React, { Component, createRef, Fragment } from 'react'
import { Card, Col, Row, Spin, Modal, List, message, Button } from 'antd'
import { UserOutlined, HistoryOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import $ from 'jquery'
import PubSub from 'pubsub-js'
import { reqContinueAnswer, reqStartAnswer, reqSubmitPaper, reqSubmitAuto, reqGetPaperInfo } from '../../api'
import { handleErr } from '../../utils'
import QuestionFinalDetail from '../../components/question-final-detail'

import './index.less'
import CountdownDetail from '../../components/count-down-detail'

const { confirm, info } = Modal

//答题页面
export default class Answer extends Component {

    scrollRef = createRef()

    state = {
        loading: false,
        QuestionTypeModularViewModels: [],
        answerResult: [],
        current: 1,
        paperId: 0,
        paperTitle: '',
        answerTimeLimit: 0,
        category: '',
        name: ''
    }

    componentDidMount() {
        const { paperId, type, id } = this.props.match.params

        if (!type) {
            this.props.history.replace('/paper')
        } else if (type === 'start') {
            //
            this.getPaperList(paperId, id)
            // this.startAnswer(+paperId, +id)
        } else if (type === 'continue') {
            this.continueAnswer(paperId)
        }

        this.saver = setInterval(() => {
            this.saveQuestion()
        }, 60000)
    }

    getPaperList = async (paperId, id) => {
        this.changeLoading(true)
        try {
            const res = await reqGetPaperInfo(new Date().getTime())
            const { success, msg, response } = res.data
            if (success) {
                let isFlag = false
                for (let v of response.PaperInfoViewModels) {
                    if (paperId == v.paperTemplateId) {
                        if (v.status === '考试中') {
                            isFlag = true
                            this.continueAnswer(v.ongoingPaperViewModel.paperId)
                        }
                    }
                }
                this.setState({
                    name: response.fullName
                })
                if (!isFlag) {
                    this.startAnswer(+paperId, +id)
                }
            } else {
                message.warning(msg)
                this.props.replace('/paper')
            }
        } catch (err) {
            this.changeLoading(false)
            handleErr(err)
        }
    }

    //loading变更
    changeLoading = (isLoading) => {
        this.setState({
            loading: isLoading
        })
    }

    //开始考试
    startAnswer = async (paperTemplateId, paperInfoId) => {
        this.changeLoading(true)
        try {
            const res = await reqStartAnswer({ paperInfoId, paperTemplateId })
            const { success, msg, response } = res.data
            if (success) {
                message.success(msg)
                this.showData('start', response)
            } else {
                message.warning(msg)
                this.props.history.replace('/paper')
            }
        } catch (err) {
            this.changeLoading(false)
            handleErr(err)
        }
    }

    //继续考试
    continueAnswer = async (id) => {
        this.changeLoading(true)
        try {
            const res = await reqContinueAnswer({ id, _t: new Date().getTime() })
            const { success, msg, response } = res.data
            if (success) {
                message.success(msg)
                this.showData('continue', response)
            } else {
                message.warning(msg)
                this.props.history.replace('/paper')
            }
        } catch (err) {
            this.changeLoading(false)
            handleErr(err)
        }
    }

    //渲染答题数据
    showData = (type, data) => {
        const { id, paperTitle, answerTimeLimit, endTime, QuestionTypeModularViewModels, name } = data
        console.log(QuestionTypeModularViewModels)
        let answerResult = [], finalData = []
        if (type === 'start') {
            for (let i of QuestionTypeModularViewModels) {
                for (let j of i.QuestionViewModels) {
                    if (i.questionType === '填空题') {
                        answerResult.push({
                            questionNumber: j.questionNumber,
                            questionId: j.id,
                            answerContent: [],
                            questionType: i.questionType,
                            optionLength: j.QuestionOptionViewModels.length
                        })
                    } else if (i.questionType === '理解题') {
                        for (let v of j.QuestionViewModel) {
                            if (v.questionType === '填空题') {
                                answerResult.push({
                                    questionNumber: v.questionNumber,
                                    questionId: v.id,
                                    answerContent: [],
                                    questionType: v.questionType,
                                    optionLength: v.QuestionOptionViewModels.length
                                })
                            } else {
                                answerResult.push({
                                    questionNumber: v.questionNumber,
                                    questionId: v.id,
                                    answerContent: null,
                                    questionType: v.questionType
                                })
                            }
                        }
                    } else {
                        answerResult.push({
                            questionNumber: j.questionNumber,
                            questionId: j.id,
                            answerContent: null,
                            questionType: i.questionType
                        })
                    }
                }

                if (i.QuestionViewModels.length > 0) {
                    finalData.push(i)
                }
            }
            PubSub.publish('firstCountDown', answerTimeLimit)
        } else if (type === 'continue') {
            for (const i of QuestionTypeModularViewModels) {
                for (const j of i.QuestionInfoViewModels) {
                    if (i.questionType === '填空题') {
                        answerResult.push({
                            questionNumber: j.questionNumber,
                            questionId: j.id,
                            answerContent: j.answerContent ? j.answerContent.split('@$#') : [],
                            questionType: i.questionType,
                            optionLength: j.QuestionOptionViewModels.length
                        })
                    } else if (i.questionType === '理解题') {
                        for (const v of j.QuestionInfosViewModels) {
                            if (v.questionType === '填空题') {
                                answerResult.push({
                                    questionNumber: v.questionNumber,
                                    questionId: v.id,
                                    answerContent: v.answerContent ? v.answerContent.split('@$#') : [],
                                    questionType: v.questionType,
                                    optionLength: v.QuestionOptionViewModels.length
                                })
                            } else {
                                answerResult.push({
                                    questionNumber: v.questionNumber,
                                    questionId: v.id,
                                    answerContent: v.answerContent ? (v.questionType === '多选题' ? v.answerContent.split(',') : v.answerContent) : null,
                                    questionType: v.questionType
                                })
                            }
                        }
                    } else {
                        answerResult.push({
                            questionNumber: j.questionNumber,
                            questionId: j.id,
                            answerContent: j.answerContent ? (i.questionType === '多选题' ? j.answerContent.split(',') : j.answerContent) : null,
                            questionType: i.questionType
                        })
                    }
                }

                if (i.QuestionInfoViewModels.length > 0) {
                    finalData.push(i)
                }
            }
            PubSub.publish('continueCountDown', endTime)
            this.setState({
                name
            })
        }

        this.setState({
            paperId: id,
            paperTitle,
            answerTimeLimit,
            QuestionTypeModularViewModels: finalData,
            answerResult,
            category: type
        }, () => {
            for (const v of answerResult) {
                let sheetLi = $(`a[id=sheet${v.questionNumber}]`)
                if (v.questionType === '多选题') {
                    if (v.answerContent && v.answerContent.length > 1) {
                        sheetLi.addClass('hasBeenAnswer')
                    }
                } else if (v.questionType === '填空题') {
                    if (v.answerContent.length === v.optionLength) {
                        let isFlag = true
                        for (const i of v.answerContent) {
                            if (!i || !i.trim()) {
                                isFlag = false
                                break
                            }
                        }
                        if (isFlag)
                            sheetLi.addClass('hasBeenAnswer')
                    }

                } else if (v.answerContent || v.answerContent === '0') {
                    sheetLi.addClass('hasBeenAnswer')
                }
            }
        })
        this.changeLoading(false)
    }

    //页面跳转
    skipPage = (index, questionNumber) => {
        this.setState({
            current: index + 1
        }, () => {
            if (questionNumber) {
                let anchorElement = document.getElementById(questionNumber);
                if (anchorElement) { anchorElement.scrollIntoView(); }
            }
        })
    }

    //state变更
    stateChange = (key, value) => {
        if (key === 'current') {
            const { current } = this.state
            this.setState({
                current: current + value
            })
            this.scrollRef.current.scrollTop = 0
        } else {
            this.setState({
                [key]: value
            })
        }
    }

    //作答
    answerChange = (questionNumber, value, questionType, index, optionLength) => {
        const { answerResult } = this.state

        if (questionType === '填空题') {
            answerResult.find(ele => ele.questionNumber === questionNumber).answerContent[index] = value
        } else {
            answerResult.find(ele => ele.questionNumber === questionNumber).answerContent = value
        }

        this.setState({
            answerResult
        }, () => {
            let sheetLi = $(`a[id=sheet${questionNumber}]`)

            if (questionType === '多选题') {
                if (value.length < 2)
                    sheetLi.removeClass('hasBeenAnswer')
                else
                    sheetLi.addClass('hasBeenAnswer')
            } else if (questionType === '填空题') {
                let answer = answerResult.find(ele => ele.questionNumber === questionNumber).answerContent
                if (answer.length < optionLength)
                    sheetLi.removeClass('hasBeenAnswer')
                else {
                    for (const v of answer) {
                        if (!v || !v.trim()) {
                            sheetLi.removeClass('hasBeenAnswer')
                            return
                        }
                    }
                    sheetLi.addClass('hasBeenAnswer')
                }
            } else {
                if (!value || !value.trim())
                    sheetLi.removeClass('hasBeenAnswer')
                else
                    sheetLi.addClass('hasBeenAnswer')
            }
        })
    }

    //提交
    handleSubmit = () => {
        const { answerResult } = this.state
        let arr = []
        for (let v of answerResult) {
            if (v.questionType === '多选题') {
                if (!v.answerContent || v.answerContent.length < 2) {
                    arr.push(v.questionNumber)
                }
            } else if (v.questionType === '填空题') {
                if (!v.answerContent || v.answerContent.length < v.optionLength) {
                    arr.push(v.questionNumber)
                } else {
                    for (let i of v.answerContent) {
                        if (!i || !i.trim()) {
                            arr.push(v.questionNumber)
                            break
                        }
                    }
                }
            } else if (!v.answerContent || !v.answerContent.trim()) {
                arr.push(v.questionNumber)
            }
        }

        console.log(arr)
        let title = '', content = ''
        if (arr.length > 0) {
            title = '以下试题未完成作答,您确定要提交吗?'
            content = '题号：' + arr.join('，')
        } else {
            title = '您确定要提交试卷吗?'
            content = '注：提交后将不能再作修改!'
        }

        confirm({
            title,  //: '您确定要提交试卷吗?',
            icon: <ExclamationCircleOutlined />,
            content,  //: '注：提交后将不能再作修改!',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.handleOk()
            }
        })
    }

    //提交试卷
    handleOk = async () => {
        const { paperId, answerResult } = this.state
        let answerQuestionViewModels = []
        for (let v of answerResult) {
            if (v.questionType === '多选题') {
                answerQuestionViewModels.push({
                    questionId: v.questionId,
                    answerContent: v.answerContent ? v.answerContent.sort((a, b) => a - b).join(',') : ''
                })
            } else if (v.questionType === '填空题') {
                answerQuestionViewModels.push({
                    questionId: v.questionId,
                    answerContent: v.answerContent.join('@$#') || ''
                })
            } else {
                answerQuestionViewModels.push({
                    questionId: v.questionId,
                    answerContent: v.answerContent || ''
                })
            }
        }

        this.changeLoading(true)
        try {
            const res = await reqSubmitPaper({ paperId, answerQuestionViewModels })
            const { success, msg } = res.data
            if (success) {
                message.success(msg)
                // this.props.history.replace('/paper')
            } else {
                // message.warning(msg)
                // this.changeLoading(false)
            }
            this.props.history.replace('/paper')
        } catch (err) {
            this.changeLoading(false)
            handleErr(err)
        }
    }

    //自动保存
    saveQuestion = async () => {
        const { paperId, answerResult } = this.state
        let answerQuestionViewModels = []
        for (const v of answerResult) {
            if (v.questionType === '多选题') {
                answerQuestionViewModels.push({
                    questionId: v.questionId,
                    answerContent: v.answerContent ? v.answerContent.sort((a, b) => a - b).join(',') : ''
                })
            } else if (v.questionType === '填空题') {
                answerQuestionViewModels.push({
                    questionId: v.questionId,
                    answerContent: v.answerContent.join('@$#') || ''
                })
            } else {
                answerQuestionViewModels.push({
                    questionId: v.questionId,
                    answerContent: v.answerContent || ''
                })
            }
        }
        console.log(answerResult)
        console.log(`paperId`, paperId)
        console.log(`answerQuestionViewModels`, answerQuestionViewModels)
        try {
            const res = await reqSubmitAuto({ paperId, answerQuestionViewModels })
            console.log(res.data.msg)
            const { success } = res.data
            if (success) {

            } else {
                info({
                    title: '您的考试流程已结束!'
                })
                this.props.history.replace('/paper')
            }
        } catch (err) {
            console.log(err)
        }
    }

    componentWillUnmount() {
        this.changeLoading(false)
        clearInterval(this.saver)
    }

    render() {
        const { loading, QuestionTypeModularViewModels, answerResult, current, paperTitle, answerTimeLimit, category, name } = this.state

        return (
            <div className="answer clearfix">
                <Spin spinning={loading}>
                    <div className="answer-card-wrapper">
                        <Row gutter={16}>
                            <Col span={5}>
                                <Card title='题目列表' bordered={false} className='my-answer-card' headStyle={{ textAlign: 'center' }} bodyStyle={{ padding: 0 }}>
                                    <List
                                        grid={{ gutter: 16, column: 1 }}
                                        dataSource={QuestionTypeModularViewModels}
                                        className='answer-sheet-list scroll-container'
                                        renderItem={(item, index) => (
                                            <List.Item>
                                                <Card title={item.questionType}>
                                                    {category === 'start' && (
                                                        item.questionType === '理解题' ? (
                                                            <ul className='answer-sheet-option-father'>
                                                                {item.QuestionViewModels.map((option, un_index) => (
                                                                    <Fragment key={un_index}>
                                                                        {option.QuestionViewModel.map(item => (
                                                                            <li key={item.questionNumber}>
                                                                                {/* <a id={`sheet${item.questionNumber}`} href={`#exer${item.questionNumber}`} onClick={(e) => this.skipPage(e, index)}>{item.questionNumber}</a> */}
                                                                                <a id={`sheet${item.questionNumber}`} onClick={(e) => this.skipPage(index, `exer${item.questionNumber}`)}>{item.questionNumber}</a>
                                                                            </li>
                                                                        ))}
                                                                    </Fragment>
                                                                ))}
                                                            </ul>
                                                        ) : (
                                                            <ul className='answer-sheet-option-father'>
                                                                {item.QuestionViewModels.map(option => (
                                                                    <li key={option.questionNumber}>
                                                                        {/* <a id={`sheet${option.questionNumber}`} href={`exer${option.questionNumber}`} onClick={(e) => this.skipPage(e, index)}>{option.questionNumber}</a> */}
                                                                        <a id={`sheet${option.questionNumber}`} onClick={(e) => this.skipPage(index, `exer${option.questionNumber}`)}>{option.questionNumber}</a>
                                                                    </li>
                                                                ))}
                                                            </ul>
                                                        )
                                                    )}
                                                    {category === 'continue' && (
                                                        item.questionType === '理解题' ? (
                                                            <ul className='answer-sheet-option-father'>
                                                                {item.QuestionInfoViewModels.map((option, un_index) => (
                                                                    <Fragment key={un_index}>
                                                                        {option.QuestionInfosViewModels.map(item => (
                                                                            <li key={item.questionNumber}>
                                                                                {/* <a id={`sheet${item.questionNumber}`} href={`#exer${item.questionNumber}`} onClick={(e) => this.skipPage(e, index)}>{item.questionNumber}</a> */}
                                                                                <a id={`sheet${item.questionNumber}`} onClick={(e) => this.skipPage(index, `exer${item.questionNumber}`)}>{item.questionNumber}</a>
                                                                            </li>
                                                                        ))}
                                                                    </Fragment>
                                                                ))}
                                                            </ul>
                                                        ) : (
                                                            <ul className='answer-sheet-option-father'>
                                                                {item.QuestionInfoViewModels.map(option => (
                                                                    <li key={option.questionNumber}>
                                                                        {/* <a id={`sheet${option.questionNumber}`} href={`exer${option.questionNumber}`} onClick={(e) => this.skipPage(e, index)}>{option.questionNumber}</a> */}
                                                                        <a id={`sheet${option.questionNumber}`} onClick={(e) => this.skipPage(index, `exer${option.questionNumber}`)}>{option.questionNumber}</a>
                                                                    </li>
                                                                ))}
                                                            </ul>
                                                        )
                                                    )}
                                                </Card>
                                            </List.Item>
                                        )}
                                    />
                                    <Card bordered={false} className='question-tips-card' bodyStyle={{ padding: '18px 65px' }}>
                                        <ul>
                                            <li></li>
                                            <li>已做</li>
                                            <li></li>
                                            <li>未做</li>
                                        </ul>
                                    </Card>
                                </Card>
                            </Col>
                            <Col span={14}>
                                <Card title='题目内容' bordered={false} className='my-answer-card' headStyle={{ textAlign: 'center' }} bodyStyle={{ padding: 0 }}>
                                    <List
                                        dataSource={QuestionTypeModularViewModels}
                                        itemLayout='vertical'
                                        split={false}
                                        pagination={{
                                            pageSize: 1,
                                            current
                                        }}
                                        renderItem={item => (
                                            <List.Item>
                                                <h2 className='item-questionType'>{item.questionType}</h2>
                                                <div className='item-questions-wrapper scroll-container' ref={this.scrollRef}>
                                                    {category === 'start' && (
                                                        item.questionType === '理解题' ? (
                                                            <>
                                                                {item.QuestionViewModels.map((option, index) => (
                                                                    <Fragment key={index}>
                                                                        <div dangerouslySetInnerHTML={{ __html: option.questionStem }} ></div>
                                                                        {option.QuestionViewModel.map((item, _i) => (
                                                                            <QuestionFinalDetail
                                                                                key={_i}
                                                                                {...item}
                                                                                answerResult={answerResult}
                                                                                answerChange={this.answerChange}
                                                                                type='child'
                                                                            />
                                                                        ))}
                                                                    </Fragment>
                                                                ))}
                                                            </>
                                                        ) : (
                                                            <>
                                                                {item.QuestionViewModels.map((option, _i) => (
                                                                    <QuestionFinalDetail
                                                                        key={_i}
                                                                        {...option}
                                                                        answerResult={answerResult}
                                                                        answerChange={this.answerChange}
                                                                    />
                                                                ))}
                                                            </>
                                                        )
                                                    )}
                                                    {category === 'continue' && (
                                                        item.questionType === '理解题' ? (
                                                            <>
                                                                {item.QuestionInfoViewModels.map((option, index) => (
                                                                    <Fragment key={index}>
                                                                        <div dangerouslySetInnerHTML={{ __html: option.questionStem }} ></div>
                                                                        {option.QuestionInfosViewModels.map((item, _i) => (
                                                                            <QuestionFinalDetail
                                                                                key={_i}
                                                                                {...item}
                                                                                answerResult={answerResult}
                                                                                answerChange={this.answerChange}
                                                                                type='child'
                                                                            />
                                                                        ))}
                                                                    </Fragment>
                                                                ))}
                                                            </>
                                                        ) : (
                                                            <>
                                                                {item.QuestionInfoViewModels.map((option, _i) => (
                                                                    <QuestionFinalDetail
                                                                        key={_i}
                                                                        {...option}
                                                                        answerResult={answerResult}
                                                                        answerChange={this.answerChange}
                                                                    />
                                                                ))}
                                                            </>
                                                        )
                                                    )}
                                                </div>
                                            </List.Item>
                                        )}
                                    />
                                    <Card bordered={false} className='my-page-turn' bodyStyle={{ padding: '12px 65px' }}>
                                        <ul>
                                            <li>
                                                <Button onClick={() => this.stateChange('current', -1)} disabled={current === 1} type={current === QuestionTypeModularViewModels.length ? 'primary' : 'default'}>上一页</Button>
                                            </li>
                                            <li>
                                                <Button onClick={() => this.stateChange('current', 1)} disabled={!QuestionTypeModularViewModels.length || current === QuestionTypeModularViewModels.length} type='primary'>下一页</Button>
                                            </li>
                                        </ul>
                                    </Card>
                                </Card>
                            </Col>
                            <Col span={5}>
                                <Card title='试卷信息' bordered={false} className='my-answer-card my-right-card' headStyle={{ textAlign: 'center' }} >
                                    <UserOutlined className='user-icon' />
                                    <p className='user-name'>
                                        姓名：{name}
                                    </p>
                                    <p className='paper-name'>
                                        试卷名称：{paperTitle}
                                    </p>
                                    <CountdownDetail
                                        answerTimeLimit={answerTimeLimit}
                                        handleOk={this.handleOk}
                                    />
                                    <p>
                                        <HistoryOutlined className='history-icon' /> <span className='history-tips'>剩余时间</span>
                                    </p>
                                    <Button size='large' block type='primary' onClick={this.handleSubmit} style={{ marginTop: 120 }}>提交试卷</Button>
                                </Card>
                            </Col>
                        </Row>
                    </div>
                </Spin>
            </div>
        )
    }
}